<template>
  <scroll-view scroll-y
               scroll-with-animation
               :scroll-into-view='scroll'
               @scroll='onScrollFn'>
    <li class="menu"
        v-for="(item,index) in category"
        :key='item.category_id'
        :id="'c'+index"
        ref='menu'>
      <!-- 标题 -->
      <h5 class="type">{{item.category_name}}</h5>
      <!-- 商品 -->
      <Goods v-for="goods in item.goods"
             :key="goods.goods_id"
             :goods='goods'></Goods>
    </li>
    <u-divider>没有更多了</u-divider>
  </scroll-view>
</template>

<script>
import eventBus from '@/common/eventbus'
import Goods from './goods.vue'
export default {
  components: { Goods },
  props: {
    category: Array,
  },
  data() {
    return {
      scroll: '', // scroll-view 需要用到的跳转 #id
      scrollHeight: [], //渲染出来的高度数组
    }
  },
  mounted() {
    // 接收 sidebar 控制内容滚动
    eventBus.$on('scroll2view', (id) => (this.scroll = 'c' + id))
    // 获取内容高度数组
    /* 
      ? 就 nm 离谱 
      ? mounted 钩子 + nextTick 都没办法读取 ref
      ? 硬加延时器
    */
    setTimeout(
      () =>
        // this.$nextTick(() =>
        this.$refs.menu.map((item) => this.scrollHeight.push(item.offsetTop))
      // )
      ,500
    )
  },
  methods: {
    // 内容滚动 控制切换 sidebar
    onScrollFn({ detail }) {
      this.scrollHeight.map((item, index) => {
        if (detail.scrollTop >= item) eventBus.$emit('scroll2sidebar', index)
      })
    },
  },
}
</script>

<style lang="scss" scoped>
scroll-view {
  flex: 1;
  padding-bottom: 20rpx;
}
.menu {
  padding: 0 20rpx;
  list-style: none;
  .type {
    height: 70rpx;
    line-height: 70rpx;
    background-color: #fff;
    font-weight: normal;
  }
}
</style>